package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class IndexController {
    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redisson;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        //TODO 查出所有的1级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();

        model.addAttribute("categorys", categoryEntities);
        //ThymeleafProperties 配置了默认前缀是 template 默认后缀是.html
        return "index";
    }

    //index/catalog.json
    @ResponseBody
    @GetMapping("index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson(){
        Map<String, List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();
        return catalogJson;
    }

    /**
     * 单机下常用的synchronized和ReentrantLock
     *      都是阻塞的，可重入的
     * 不建议使用redis的set和del来实现分布式锁。
     * Redisson的RLock有看门狗机制，无需自己设置过期时间，且看门狗会自动续期
     * 要注意的是 如果给RLock设置了过期时间（非-1） 查看源码发现 其不会自动续期
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //1、获取一把锁，只要锁名一样，就是同一把锁
        RLock lock = redisson.getLock("my-lock");
        //2、加锁
        lock.lock();//阻塞等待
        //RLock会自动续期，且加锁的业务只要业务完成，就不会再续期，锁也会在最多30秒内（默认）自动删除
        try{
            System.out.println("加锁成功，执行业务");
        }finally {
            //3、解锁
            lock.unlock();//好处就是 不用等到自动续期
            System.out.println("解锁成功");
        }
        return "hello";
    }

    /**
     * 经过测试 读写锁此处实现是公平的
     * 即 按照 读写读读的情况下 抢锁顺序还是读写读读
     * 虽然读和读之间共享 写和其他都互斥
     * @return
     */
    @ResponseBody
    @GetMapping("/write")
    public String write(){
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = lock.writeLock();
        try{
            //写锁加锁
            rLock.lock();
            System.out.println("写锁加锁成功..."+Thread.currentThread().getId());
            s = UUID.randomUUID().toString();
            Thread.sleep(15000);
            redisTemplate.opsForValue().set("writeValue", s);
        }catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            rLock.unlock();
            System.out.println("释放写锁成功..."+Thread.currentThread().getId());
        }

        return s;
    }

    @ResponseBody
    @GetMapping("/read")
    public String read(){
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = lock.readLock();
        try{
            //读锁加锁
            rLock.lock();
            System.out.println("读锁加锁成功..."+Thread.currentThread().getId());
            Thread.sleep(5000);
            s = redisTemplate.opsForValue().get("writeValue");
        }catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            rLock.unlock();
            System.out.println("释放读锁成功..."+Thread.currentThread().getId());
        }

        return s;
    }
}
